// pages/mine/course_manager.js
const {request, showTip} = require("../common/request");
const qiniuUtil = require('../common/qiniu');

Page({
    /**
     * 页面的初始数据
     */
    data: {
        userInfo: {}
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        initUserInfo(this);
    },
    // 下拉刷新触发时执行
    onPullDownRefresh() {
        wx.showLoading({ title: '刷新中...' });
        initUserInfo(this);
        wx.stopPullDownRefresh();// 停止刷新动画
        wx.hideLoading();
    },
    onChooseAvatar(e) {
        const that = this;
        const userInfoTemp = wx.getStorageSync("userInfo");
        //userInfoTemp.avatarUrl = e.detail.avatarUrl;
        const filePath = e.detail.avatarUrl;//获取文件地址
        const fileName = new Date().getTime() + '.jpg';//自定义文件名称
        console.log("filePath:"+filePath);
        console.log("开始把微信小程序临时文件上传到七牛云");
        request({
            url:'/yoga_business/wechat/qiniu/getUploadToken',
            method:'GET',
            data:{},
            success(res) {
                if(res.success){
                    console.log("uptoken:"+res.content);
                    const uptokenTemp = res.content;
                    // 3. 上传到七牛云
                    wx.uploadFile({
                        url: 'https://up-z2.qiniup.com',
                        filePath,
                        name: 'file',
                        formData: {
                            key: fileName,
                            token: uptokenTemp
                        },
                        success: (uploadRes) => {
                            console.log( uploadRes);
                            if (uploadRes.statusCode === 200) {
                                const result = JSON.parse(uploadRes.data);
                                const fileKey = `${result.key}`;
                                console.log('result↓');
                                console.log(result);
                                console.log('fileKey：'+fileKey);
                                //获取真实地址
                                request({
                                    url:'/yoga_business/wechat/qiniu/generateSignedUrl',
                                    method:'POST',
                                    data:{
                                        "fileKey": fileKey
                                    },
                                    success(res) {
                                        if(res.success){
                                            //TODO 这里会有问题，存储在表中只能是fileKey，否则会失效，应该每次访问涉及图片时候都后端重新获取进行加载才行
                                            userInfoTemp.avatarUrl = res.content;
                                            wx.setStorageSync("userInfo",userInfoTemp);
                                            that.setData({
                                                userInfo: userInfoTemp
                                            });
                                        }else{
                                            showTip();
                                        }
                                    },
                                    fail(msg) {
                                        showTip();
                                    }
                                });
                            } else {
                                wx.showToast({ title: '上传失败', icon: 'none' });
                            }
                        },
                        fail: (err) => {
                            console.error('上传失败:', err);
                            wx.showToast({ title: '上传请求失败', icon: 'none' });
                        }
                    });
                }else{
                    showTip(res.message);
                }
            },
            fail(msg) {
                console.log('POST请求失败', msg);
            }
        });
    },
    //http://tmp/yrZQKnDAzb6Yde928a2e92e47d5dcda7a3ce9b023787.jpeg
    //http://tmp/xbOwBJNZgwVp70b492c8c5ea45bf34e745164e1d0309.jpg
    onNickNameInput(e) {
        const userInfoTemp = wx.getStorageSync("userInfo");
        userInfoTemp.nickName = e.detail.value;
        wx.setStorageSync("userInfo",userInfoTemp);
        this.setData({
            userInfo: userInfoTemp
        });
    },
    onPhoneNumberInput(e) {
        const userInfoTemp = wx.getStorageSync("userInfo");
        userInfoTemp.phoneNumber = e.detail.value;
        wx.setStorageSync("userInfo",userInfoTemp);
        this.setData({
            userInfo: userInfoTemp
        });
    },
    onSave() {
        const that = this;
        const { openId,avatarUrl, nickName, phoneNumber } = that.data.userInfo;
        // 这里可以添加表单验证逻辑，例如手机号格式验证
        if (!/^1[3-9]\d{9}$/.test(phoneNumber)) {
            wx.showToast({
                title: '手机号格式不正确',
                icon: 'none'
            });
            return;
        }
        request({
            url:'/yoga_business/wechat/wechatUser/save',
            method:'POST',
            data:{
                "openId": openId,
                "nickName":nickName,
                "avatarUrl":avatarUrl,
                "phoneNumber":phoneNumber
            },
            success(res) {
                if(res.success){
                    //说明缓存存在，则进行赋值
                    wx.setStorageSync("userInfo",res.content);//更新缓存
                    that.setData({
                        userInfo:wx.getStorageSync("userInfo")
                    });
                    wx.switchTab({
                        url: '/pages/mine/mine'
                    });
                }else{
                    showTip();
                }
            },
            fail(msg) {
                showTip();
            }
        });
    }
})

/**
 * 初始化用户信息
 * @param _this
 */
const initUserInfo = (_this) => {
    //先获取换成的用户数据，没有则进行显示未登录
    const userInfoTemp = wx.getStorageSync("userInfo");
    _this.setData({
        "userInfo":userInfoTemp
    })
};